<template>
   
  <div>
    <el-button @click="openDialog">上传文件</el-button>
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible">
      <div
        class="list_content"
        v-loading="isDisable"
        element-loading-text="资源解析中..."
      >
        <uploader
          :options="options"
          :autoStart="false"
          ref="uploader"
          class="uploader-example"
          @file-added="onFileAdded"
          @file-success="onFileSuccess"
          @file-progress="onFileProgress"
          @file-error="onFileError"
        >
        <uploader-btn ref="uploadBtn" id="global-uploader-btn" :attrs="attrs"
            >
            <div>
              <div class="flexWithJusCenter"><i class="el-icon-upload uploadIcon"></i>
              </div>
            <p>点击上传文件，文件请预先命名</p>
            </div>
            </uploader-btn
          >
          <uploader-unsupport></uploader-unsupport> 
          <!-- //浏览器不支持将显示此内容 -->

          <uploader-list>
            <!-- <template slot-scope="props">
              <ul>
                <li
                  v-for="file in props.fileList"
                  :key="file.id"
                  class="liItem"
                >
                  <uploader-file
                    :file="file"
                    :list="true"
                    ref="uploaderFile"
                    :pauseFlag="pauseFlag"
                  >
                    <template slot-scope="props"
                      >
                      <div class="filebox">
                        <p class="fileNameBox">
                          <span class="fileIcon"></span>
                          {{ file.name }}
                        </p>
                        <p class="fileProgressBox">
                          <el-progress
                            class="progressLength"
                            :percentage="
                              parseInt(
                                props.progress.toFixed(2) * 100 - 1 < 0
                                  ? 0
                                  : props.progress.toFixed(2) * 100 - 1
                              )
                            "
                          ></el-progress>
                          <span
                            :class="{
                              statusBtn: !pauseFlag,
                              resumeBtn: pauseFlag,
                            }"
                            class="progressBtn"
                            @click="pause(file, file.resourceId)"
                          ></span>
                          <span
                            class="cancelBtn progressBtn"
                            @click="remove(file, file.resourceId)"
                          ></span>
                        </p>
                        <p class="fileInfoBox">
                          <span class="fileInfoItem"
                            >速度：{{
                              pauseFlag ? 0 : props.formatedAverageSpeed
                            }}</span
                          >
                          <span class="fileInfoItem"
                            >已上传：{{
                              (
                                parseFloat(props.formatedSize) * props.progress
                              ).toFixed(1)
                            }}/{{ props.formatedSize }}</span
                          >
                          <span class="fileInfoItem"
                            >剩余时间：{{
                              pauseFlag ? 0 : props.formatedTimeRemaining
                            }}</span
                          >
                        </p>
                      </div>
                    </template>
                  </uploader-file>
                </li>
              </ul>
            </template> -->
          </uploader-list>
          <!-- //开始上传按钮 -->
          
        </uploader>
      </div>
      <!-- <div slot="footer" class="dialog-footer upLoadFooter">
        <el-button
          plain
          size="medium"
          @click="cancelAddRes"
          class="el-button cancel_btn"
          >取 消</el-button
        >
        <el-button
          :class="{ none: isUploading }"
          size="medium"
          @click="continueAddRes"
          class="el-button continueAddRes_btn"
          id="continueAddRes_btn"
          >添加</el-button
        >
      </div> -->
    </el-dialog>
  </div>
</template>
<script>
var resourceId = ""; //保存资源id
import md5 from 'js-md5';
import { getToken } from '@/utils/auth'

export default {
  name: "singleFileUpload",
  props: {},
  watch: {},
  computed: {},
  data() {
    return {
      dialogVisible: false,
      isDisable: false,
      isUploading: false,
      pauseFlag: true,

      options: {
        target: process.env.VUE_APP_BASE_API+"/file/uploadBigFile",
        headers: { 'Authorization': getToken() },
        testChunks: false, //是否开启服务器分片校验
        maxChunkRetries: 5, //最大自动失败重试上传次数
        chunkSize: 3 * 1024 * 1024, //分片大小
        singleFile: true, //单文件上传
        simultaneousUploads: 1,

        processParams(params) {
          //每一次分片传给后台的参数，params是该方法返回的形参，包含分片信息
          return {
            //返回一个对象，会添加到每一个分片的请求参数里面
            name: params.filename,
            code: params.identifier,
            total: params.totalChunks,
            index: params.chunkNumber,
            resourceId,
          };
        },
      },

      attrs: {
        accept: "",
        // accept: ".zip",
      },
    };
  },
  methods: {
    openDialog() {
      this.dialogVisible = true;
    },

    //文件添加时回调，这里可以做格式校验，md5计算
    onFileAdded(file) {
      let _this = this
      console.log('onFileAdded--',file);
      let typeName = file.file.name;
      let reg = /\.zip$/;
      // if (!reg.test(typeName)) {
      //   file.ignored = true;
      //   this.$alert("上传文件格式不正确，请检查", "上传错误", {
      //     confirmButtonText: "确定",
      //     callback: (action) => {},
      //   });
      // } else {
        // 计算MD5;
        this.computeMD5(file, _this);
      // }
    },
    //所有分片上传完成的回调，需要注意的是，由于异步上传，每一次分片上传不会等上一次响应回来才发送，
    //因此该上传成功的回调时，返回的分片响应可能不是最后一片，因此后续会发送合并请求告诉后台进行合并文件
    onFileSuccess(rootFile, file, message, chunk) {
      console.log('onFileSuccess--',rootFile, file, message, chunk);
      if(chunk.xhr.status == 200){
        this.dialogVisible = false;
        let data = {
          name:file.name,
          url:message
        }
        this.$emit("returnUrl", data)
      }
      //所有分片上传成功，发送合并分片请求，具体参数与后台确定，后台合并文件
    },

    //文件上传的过程中会频繁调用该函数
    onFileProgress(rootFile, file, chunk) {
      console.log('onFileProgress--',rootFile, file, chunk);
    },

    //文件上传出错的回调
    onFileError(rootFile, file, msg, chunk) {
      console.log('onFileError--',rootFile, file, msg, chunk);
    },

    computeMD5(file, _this) {
      // let that = this;
      let fileReader = new FileReader();
      let md5Name = "";
      file.pause(); //先暂停，后续生成uniqueIdentifier
      fileReader.readAsArrayBuffer(file.file);

      console.log('file--',file);
      
      fileReader.onload = (e) => {
        console.log('e--',e);
        if (file.size != e.target.result.byteLength) {
          _this.$message.error("文件读取失败");
          return;
        }

        md5Name = md5(file.name); //业务需求以文件名作为加密
        file.uniqueIdentifier = md5Name;

        if (md5Name != "") {
          file.resume(); //继续上传文件
        }
      };
      console.log('fileReader--',fileReader);
      fileReader.onerror = function () {
        _this.$message.error("文件读取失败");
      };
    },

    cancelAddRes(){},

    continueAddRes(){}
  },
};
</script>
<style scoped>
.uploader-btn{
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.uploadIcon{
  font-size: 50px;
}
</style>

